package com.matu.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.matu.domain.Arret;
import com.matu.domain.Ligne;
import com.matu.service.ServiceTisseo;
import com.matu.util.DBManager;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String home1(Locale locale, Model model, HttpServletRequest request) {
		return home(locale, model,  request);
	}
	
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model, HttpServletRequest request) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		
		ServiceTisseo sTisseo = new ServiceTisseo();

		
		/*
		 * Chercher les lignes
		 */
		ArrayList<Ligne> listeDesLignes = new ArrayList<Ligne>();
		try {
			listeDesLignes = sTisseo.getServiceListeLignes();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		model.addAttribute("listLigne", listeDesLignes);
		
		/*
		 * Chercher les arrets à proximité
		 */

		String idSelectedLigne = (String) request.getParameter("idLigne");
		ArrayList<Arret> listeArret = new ArrayList<Arret>();

		if (idSelectedLigne != null) {

			try {
				listeArret = sTisseo.getServiceArretsDeLigne(idSelectedLigne);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		model.addAttribute("listArret",listeArret);
		
		
		/*
		 * Gestion des likes
		 */
		
		DBManager man = new DBManager();
		
		if (idSelectedLigne != null) {
			
			Ligne ligneSel = man.getLigneSel(idSelectedLigne, listeDesLignes);
			boolean isLigneInBD = man.isLigneInDB(ligneSel);
			
			if (isLigneInBD) {
				Ligne ligneBD = man.getLigneInBD(idSelectedLigne);
				model.addAttribute("ligneBD", ligneBD);
			}
		}
		
		return "home";
	}
	
	
}
